package com.ctshk.rpc.order.season.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SeasonOrderManager;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.finance.req.bill.BillOperateRefundReq;
import com.ctshk.rpc.finance.service.IFinanceBillService;
import com.ctshk.rpc.order.season.dto.SeasonOrderPayDTO;
import com.ctshk.rpc.order.season.entity.SeasonOrder;
import com.ctshk.rpc.order.season.entity.SeasonOrderCollection;
import com.ctshk.rpc.order.season.mapper.SeasonOrderCollectionMapper;
import com.ctshk.rpc.order.season.mapper.SeasonOrderMapper;
import com.ctshk.rpc.order.season.service.ISeasonOrderCollectionService;
import com.ctshk.rpc.system.dto.MainDataCurrencyListDTO;
import com.ctshk.rpc.system.dto.member.ContactQueryDTO;
import com.ctshk.rpc.system.req.MainDataCurrencyListReq;
import com.ctshk.rpc.system.req.crm.member.CrmMemberQueryReq;
import com.ctshk.rpc.system.req.crm.member.CrmMemberUpdatePointsReq;
import com.ctshk.rpc.system.service.ICrmMemberService;
import com.ctshk.rpc.system.service.IMainDataCurrencyService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;


/**
 * <p>
 * 套票收款明细 服务实现类
 * </p>
 *
 * @author 杨林
 * @since 2021-03-24
 */
@DubboService
public class SeasonOrderCollectionServiceImpl extends ServiceImpl<SeasonOrderCollectionMapper, SeasonOrderCollection> implements ISeasonOrderCollectionService {

    @Autowired
    private SeasonOrderCollectionMapper seasonOrderCollectionMapper;
    @Autowired
    private SeasonOrderMapper seasonOrderMapper;

    @DubboReference
    private IMainDataCurrencyService mainDataCurrencyService;

    @DubboReference
    private ICrmMemberService crmMemberService;
    @DubboReference
    private IFinanceBillService financeBillService;

    /* @MethodName: 收款记录表
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/29 18:11
     **/
    @Override
    public List<SeasonOrderPayDTO> getCollectionListById(Long id) {
        List<SeasonOrderCollection> list = seasonOrderCollectionMapper.selectList(
                new QueryWrapper<SeasonOrderCollection>().lambda()
                        .eq(SeasonOrderCollection::getIsDeleted, IsDeletedCode.NO.getCode())
                        .eq(SeasonOrderCollection::getOrderId, id)
        );
        return EntityUtil.copyList(list, SeasonOrderPayDTO.class);
    }


    /* @MethodName: 套票收款 再次确认
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/3/31 9:11
     **/
    @Override
    public Result reconfirmCollection(Long id) {
        SeasonOrderCollection seasonOrderCollection = seasonOrderCollectionMapper.selectById(id);
        SeasonOrder seasonOrder = seasonOrderMapper.selectById(seasonOrderCollection.getOrderId());
        seasonOrderCollection.setStatus(OrderCollectionStatus.UN_REJECT.getCode());
        seasonOrderCollectionMapper.updateById(seasonOrderCollection);
        BillOperateRefundReq billOperateRefundReq = new BillOperateRefundReq();
        billOperateRefundReq.setBillNumber(seasonOrderCollection.getCollectionNumber());
        Integer productType = seasonOrder.getProductType();
        billOperateRefundReq.setBusinessType(SeasonType.PRODUCT_FIXED_TYPE.getCode() == productType ? SystemBusinessType.FIXED_PACKAGE_TICKET.getCode() : SystemBusinessType.DYNAMIC_PACKAGE_TICKET.getCode());
        billOperateRefundReq.setUserId(seasonOrder.getSalesmanId());
        financeBillService.reConfirm(billOperateRefundReq);
        return Result.success();
    }


    /* @MethodName: 使用积分
     * @Description: TODO
     * @Param:
     * @Return:
     * @Author: 杨林
     * @Date:2021/4/1 13:35
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public BigDecimal userPoints(Long id, TokenUser user) {
        BigDecimal hkdAmount = BigDecimal.ZERO;
        ContactQueryDTO contactQuery;
        try {
            SeasonOrder order = seasonOrderMapper.selectById(id);
            CrmMemberQueryReq crmMemberQueryReq = new CrmMemberQueryReq(order.getMemberQueryType(), order.getMemberQueryCode(), order.getMemberQueryCertificatesType().toString());
            contactQuery = crmMemberService.queryMember(crmMemberQueryReq);
            String crmUserId = String.valueOf(user.getId()).substring(0, 12);
            Integer points = order.getUsingPoints();

            BigDecimal readyMoney = new BigDecimal(points / 100); //人民币
            // 获取兑港币汇率
            MainDataCurrencyListDTO mainDataCurrencyListDTO = getExchangeRateByName(Currency.HKD.getCurrency());
            BigDecimal crmExchangeRateCNY = mainDataCurrencyListDTO.getCrmExchangeRate();
            hkdAmount = readyMoney.multiply(crmExchangeRateCNY);
            CrmMemberUpdatePointsReq crmMemberUpdatePointsReq = new CrmMemberUpdatePointsReq();
            crmMemberUpdatePointsReq.setUpdateType(2);
            crmMemberUpdatePointsReq.setNumPoints(new BigDecimal(order.getUsingPoints()));//do积分点数
            crmMemberUpdatePointsReq.setXCtsProdDesc(order.getProductName());//do板塊產品描述 (建議使用: 集團產品名稱 + “ – “ + 板塊產品名稱, 例如: 港澳参团游 - 主题游)")
            crmMemberUpdatePointsReq.setTxnNum(order.getOrderNumber() + "-1");//do交易編號 (如為旅行團交易, 目前我們的格式是 旅行團交易編號 + ‘-‘ + 序號, 例如: 01P08192131025A155506-1
            crmMemberUpdatePointsReq.setAmtVal(hkdAmount);
            crmMemberUpdatePointsReq.setXCtsRmbAmount(readyMoney);
            crmMemberUpdatePointsReq.setCreateUserid(crmUserId);
            crmMemberUpdatePointsReq.setXCtsTxnOrgCode("219910000010");
            crmMemberUpdatePointsReq.setTxnChannelCd("16");
            crmMemberUpdatePointsReq.setXCtsTxnChnNum("211099000010");
            crmMemberUpdatePointsReq.setProdName("8821090000");
            crmMemberUpdatePointsReq.setXCtsProdCode("8821090300");
            //  crmMemberService.updatePoints(crmMemberUpdatePointsReq, contactQuery);

            // 新增CRM会员付款方式
            SeasonOrderCollection seasonOrderCollection = new SeasonOrderCollection();
            seasonOrderCollection.setId(SnowflakeIdWorker.nextId());
            seasonOrderCollection.setOrderId(order.getId());
            seasonOrderCollection.setCollectionAmount(hkdAmount);
            seasonOrderCollection.setCurrency(Currency.HKD.getCurrency());
            seasonOrderCollection.setCurrencyId(Currency.HKD.getCode());
            seasonOrderCollection.setStatus(OrderCollectionStatus.UN_REJECT.getCode());
            seasonOrderCollection.setCollectionWayId(SeasonOrderManager.pointsCollectionWayId); //支付方式：CRM星賞會積分
            seasonOrderCollection.setCollectionWay(SeasonOrderManager.pointsCollectionWayName);
            seasonOrderCollection.setIsDeleted(IsDeletedCode.NO.getCode());
            seasonOrderCollection.setCreateId(user.getId());
            seasonOrderCollection.setGmtCreate(LocalDateTime.now());
            seasonOrderCollectionMapper.insert(seasonOrderCollection);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                throw e;
            } else {
                throw new BusinessException(SystemError.AIREXPRESS_ORDER_60009);
            }
        }

        return hkdAmount;


    }


    /**
     * 根据币种名称获取汇率
     *
     * @param currencySy
     * @return
     */
    private MainDataCurrencyListDTO getExchangeRateByName(String currencySy) {
        MainDataCurrencyListReq mainDataCurrencyListReq = new MainDataCurrencyListReq();
        mainDataCurrencyListReq.setName(currencySy);
        PageResponse<MainDataCurrencyListDTO> list = mainDataCurrencyService.list(mainDataCurrencyListReq);
        if (CollectionUtils.isEmpty(list.getRecords())) {
            throw new BusinessException(SystemError.AIREXPRESS_ORDER_60003);
        }
        return list.getRecords().get(0);
    }
}
